package com.qupai.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qupai.entity.OrderDetail;
import com.qupai.entity.Orders;
import com.qupai.entity.Prizes;
import com.qupai.mapper.OrderDetailMapper;
import com.qupai.mapper.OrderMapper;
import com.qupai.mapper.PrizesMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;


/**
 * 定时任务类，定时处理订单状态
 */
@Component
@Slf4j
public class OrderTask {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private PrizesMapper prizesMapper;

    /**
     * 处理订单超时的方法
     */
    @Scheduled(cron = "0 * * * * ? ")//每分钟触发一次
    public void processTimeoutOrder() {
        log.info("定时处理超时订单：{}", LocalDateTime.now());

        //超时15分钟自动取消
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        // 实现订单超时处理逻辑
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(Orders::getStatus, Orders.PENDING_PAYMENT)
                .lt(Orders::getOrderTime, time);
        List<Orders> ordersList = orderMapper.selectList(wrapper);

        //遍历获取到的超时订单，操作mapper更改
        if (ordersList != null && !ordersList.isEmpty()) {
            for (Orders orders : ordersList) {

                //实现订单明细表中奖品数量返还奖品库存
                Long ordersId = orders.getId();
                //根据订单id批量查
                QueryWrapper<OrderDetail> wrapper4 = new QueryWrapper<>();
                wrapper4.lambda().eq(OrderDetail::getOrderId, ordersId);
                List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper4);
                for (OrderDetail orderDetail : orderDetails) {
                    Long prizesId = orderDetail.getPrizesId();
                    Long detailNumber = orderDetail.getNumber();
                    System.out.println("奖品id：" + prizesId + "，数量：" + detailNumber);
                    Prizes prizes = prizesMapper.selectById(prizesId);
                    prizes.setStock(prizes.getStock() + detailNumber);
                    prizesMapper.updateById(prizes);
                }

                //修改订单状态
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时,自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.updateById(orders);

            }
        }
    }

}
